'use strict';

var fs = require('fs');
var uuid = require('uuid');
var router = require("./route");
var url = require("url");
var redis = require("../utils/zredis.js")();
//var redis = Zredis();

var KEY = 'key-data';
var clients = []; 
// you'll probably load configuration from config
var cfg = {
    ssl: true,
    port: 3000,
    ssl_key: '2_xuzhenglucky.com.cn.key',
    ssl_cert: '1_xuzhenglucky.com.cn_bundle.crt'
};

var httpServ = (cfg.ssl) ? require('https') : require('http');

var WebSocketServer = require('ws').Server;

var app = null;

// dummy request processing
var processRequest = function(req, res) {
    var pathname = url.parse(req.url).pathname;
    console.log("Request for " + pathname + " received.");
 
    router.route(pathname,req, res);
};

if (cfg.ssl) {
    app = httpServ.createServer({
        // providing server with  SSL key/cert
        key: fs.readFileSync(cfg.ssl_key),
        cert: fs.readFileSync(cfg.ssl_cert)

    }, processRequest).listen(cfg.port);
} else {
    app = httpServ.createServer(processRequest).listen(cfg.port);
}

// passing or reference to web server so WS would knew port and SSL capabilities
var wss = new WebSocketServer({
    server: app
});

var Stat = {
	'CONNET':0,
	'OPEN':1,
	
};


function broadcastSend(type, message) {
    clients.forEach(function(v, i) {
        if(v.ws.readyState === Stat.OPEN) {     
		 
		   var jsonstr=JSON.stringify(message);
		   //console.log('jsonstr:'+jsonstr);
		   v.ws.send(jsonstr);
		  
        }
    })
}
wss.on('connection', function(ws) {
	
	var client_uuid = uuid.v4();
    
    clients.push({
        "id": client_uuid,
        "ws": ws
    });

    console.log(`client ${client_uuid} connected`);
    /**
     * 关闭服务，从客户端监听列表删除
     */
    function closeSocket() {
        for(var i = 0; i < clients.length; i++) {
          if(clients[i].id == client_uuid) {
            //var disconnect_message = `${nickname} has disconnected`;
            //broadcastSend("notification", disconnect_message);
			console.log('disconnect_message.....');  
            clients.splice(i, 1);
          }
        }
    }
		
    ws.on('message', function(message) {
        console.log(message);
        ws.send('reply');
    });
	
	
	
	 ws.on('close', function() {
        closeSocket();
    });
	

});



setInterval(function(err,data){
	
	redis.GetData(KEY,function(err,res){
		
		if(err){
			console.log('redis.GetData:'+err);  
		}else{
			
			//console.log(typeof res);
			//console.log('redis.res:'+res);
			broadcastSend('message',res)	
		}
		
	});
	
},500);



/*
var mqtt  = require('mqtt');  
var client  = mqtt.connect('mqtt://localhost:61613',{  
	username:'admin',  
	password:'password',  
	clientId:'app_1'  
});  

client.on('connect', function () {  
	console.log('connected.....');  
	client.subscribe('test');  
	//client.publish('test/', 'Hello mqtt');  
});  

client.on('message', function (topic, message) {  
	// message is Buffer  
	console.log(message.toString());  
	//client.end();
	
	//wss.broadcast(message.toString());
	
	broadcastSend('message',message);

});  
*/

